require 'fileutils'
include FileUtils
require 'rake/clean'
#require 'yaml'
require 'rubygems'

##################    CONSTANTS                ############################
############## Ruby Constants convention: CONSTANTS_NAME ##################
############## global variable: $global_variable_name    ##################
LOC_WORKING_DIRECTORY = Rake.application.original_dir

LOC_SOURCE_DIR = File.join(LOC_WORKING_DIRECTORY,   "0.SourceCode")
LOC_BUILD_OUTPUT = File.join(LOC_WORKING_DIRECTORY,   "1.BuildOutput")
LOC_PREPACKAGE_DIR = File.join(LOC_WORKING_DIRECTORY, "2.PrePackage")
LOC_UNZIPPED_DIR = File.join(LOC_WORKING_DIRECTORY, "3.UnzippedPackage")

LOC_PROJ_DIR = File.join(LOC_SOURCE_DIR,"MapTeams.Umbraco.Polls")
LOC_PROJ_FILE = File.join(LOC_PROJ_DIR,"MapTeams.Umbraco.Polls.csproj")

ZIP_FILE_NAME ="MapTeamsPollsPackage0.6.zip" #do not use space if possible
ZIP_FILE_NAME_MANUAL ="Manual_Install_#{ZIP_FILE_NAME}" #do not use space if possible
################## END CONSTANTS #########################

## msbuild.exe location (.net 4.0) 
win_dir = ENV['windir'] || ENV['WINDIR']
win_dir = 'C:/Windows' if win_dir.nil?
$msbuild_path = File.join(win_dir.dup, 'Microsoft.NET', 'Framework', 'v4.0.30319', 'MSBuild.exe')

#parameters
#global variable
$compile_target_env = "Release"


############# validation
############# end validation


########################### list of task
task :default => [ :Copy_Source_Code, 
                   :Change_Class_Inheritance, 
                   :Build_MapTeams_PollsProject, 
                   :Copy_To_PrePackage_Directory, 
                   :Prepare_Unzipped_Package, 
                   :Zip_Package,
                   :Zip_Package_For_Manual_Install]

########################## end list of task


desc "copy all needed source and references to temporary folder to be edited and recompiled"
task :Copy_Source_Code do
	
	#copy source code from real source code location to 0.SourceCode because we need to edit source and compile
	OverWriteFolderContent(File.join(LOC_WORKING_DIRECTORY,"../MapTeams.Umbraco.Polls"),LOC_PROJ_DIR )
	
	#copy references folder so project can be build
	OverWriteFolderContent(File.join(LOC_WORKING_DIRECTORY,"../References"),File.join(LOC_SOURCE_DIR,"References") )
end

desc "Change class inheritance for any aspx.cs files in specified folder with name started with 'Admin'"
task :Change_Class_Inheritance do

	classFiles = File.join(
	             LOC_PROJ_DIR,
	             "umbraco/plugins/MapTeamsPolls/Admin*.aspx.cs")
	fileCollection = Dir[classFiles]
	#puts fileCollection
	
	fileCollection.each do|sourceFile|		
		text = File.read( sourceFile)		
		text = text.gsub(/(^\s*public partial class .*:\s*)(.*)/, '\1UmbracoEnsuredPage')				
		File.open(sourceFile, 'w') { |f| f.write(text) }			
	end	
end


desc "Build and deploy MapTeams.Umbraco.Polls project -> copy the build output to folder(1.BuildOutput)"
task :Build_MapTeams_PollsProject do
	output = LOC_BUILD_OUTPUT
	projFile = LOC_PROJ_FILE

	RecreateEmptyFolder(output)
	
	cmd_string = $msbuild_path + " \"#{projFile}\" " + 
     	   "/p:configuration=Release /p:webprojectoutputdir=\"#{output}\" /p:outdir=\"#{output}/bin/\" " +
         "/target:Clean;Rebuild;ResolveReferences;_CopyWebApplication"
	sh cmd_string
	
end

#copy 1.BuildOutput\bin =>     2.PrePackage\tempfolder\bin
#copy 1.BuildOutput\umbraco => 2.PrePackage\tempfolder\umbraco
#copy template package.xml to prepackage dir
desc "Copy only selected files/folders to prePackageDirectory "
task :Copy_To_PrePackage_Directory do
		
	target = "2.PrePackage/tempfolder"
	
	#delete temp target dir if exist	
	RecreateEmptyFolder(target)
	
	OverWriteFolderContent("1.BuildOutput/bin" ,target+"/bin")
	OverWriteFolderContent("1.BuildOutput/umbraco" ,target+"/umbraco")
	
	FileUtils.cp 'templatePackage.xml', target+"/package.xml", :verbose=>true
end

desc "Use AddFilesToPackage.exe to flatten directory structures and add files to package.xml"
task :Prepare_Unzipped_Package do
	addFilesToPackage = File.join(LOC_WORKING_DIRECTORY, "AddFilesToPackage.exe")
	packageFile = File.join(LOC_PREPACKAGE_DIR,"tempfolder","package.xml")
	prepackageFolder = File.join(LOC_PREPACKAGE_DIR,"tempfolder")
		
	RecreateEmptyFolder(LOC_UNZIPPED_DIR)
	#you cannot call the program like this below!!!!!!!!!!!!!!!!!!!!!!!
	#use full path instead(undocumented) 
	#"AddFilesToPackage.exe" "2.PrePackage\tempfolder\package.xml" "2.PrePackage\tempfolder" "3.UnzippedPackage"
	
	cmd_string = "\"#{addFilesToPackage}\" \"#{packageFile}\" \"#{prepackageFolder}\"  \"#{LOC_UNZIPPED_DIR}\" "
	sh cmd_string
end

desc "zip the umbraco package folder prepared by AddFilesToPackage.exe "
task :Zip_Package do
	FileUtils.rm_f File.join(LOC_WORKING_DIRECTORY, ZIP_FILE_NAME)
	Dir.chdir "#{LOC_UNZIPPED_DIR}"
	sh "..\\7za.exe a ..\\#{ZIP_FILE_NAME} *"
	Dir.chdir ".."
end

desc "create zip for manual umbraco installation "
task :Zip_Package_For_Manual_Install do
	target = "4.ManualPackageInstall"
	
	#delete temp target dir if exist	
	RecreateEmptyFolder(target)
	
	OverWriteFolderContent("1.BuildOutput/bin" ,target+"/bin")
	OverWriteFolderContent("1.BuildOutput/umbraco" ,target+"/umbraco")
	FileUtils.cp '@umbraco manual install.txt', target+"/@umbraco manual install.txt", :verbose=>true
	
	FileUtils.rm_f File.join(LOC_WORKING_DIRECTORY, ZIP_FILE_NAME_MANUAL) #remove existing zip 
	Dir.chdir "#{target}"
	sh "..\\7za.exe a ..\\#{ZIP_FILE_NAME_MANUAL} *"
	Dir.chdir ".."
end


################ functions ##############################

	def OverWriteFolderContent(source, target)
		#remove target dir if exist
		RecreateEmptyFolder(target)
		FileUtils.cp_r source+"\\." , target , :verbose => true
	end
	
	def RecreateEmptyFolder(target)
		FileUtils.rm_rf(target, :verbose=>true) if (Dir[target] != [] and Dir[target] != nil )
		sleep 3 #make sure no other process is holding the folder
		FileUtils.mkdir_p target , :verbose=>true
	end
############### end functions ############################